package com.yangye.pigenerator;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yangye.pigenerator.model.Configs;
import com.yangye.pigenerator.model.GenConfig;
import com.yangye.pigenerator.util.GenUtil;
import com.yangye.pigenerator.util.XMLUtil;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.util.StopWatch;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author yangye
 * @date 2020/03/16
 */
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@Slf4j
public class PiGeneratorApplication implements ApplicationRunner {
	@Autowired
	private Configs configs;

	public static void main(String[] args) {
		SpringApplication.run(PiGeneratorApplication.class, args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		log.info("开始代码生成...");
		/**
		 * 使用mybatis-generator生成entity,mapper
		 */
		List<GenConfig> genConfigs = this.translateFromMapList(this.configs.getConfigs());
		List<String> warnings = new ArrayList<String>();
		boolean overwrite = true;
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(new FileInputStream(XMLUtil.touchMbgFile(configs.getModuleName(), genConfigs)));
		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		myBatisGenerator.generate(null);

		/**
		 * 使用freemarker生成service,controller
		 */
		GenUtil.genCode(configs.getModuleName(), genConfigs);
		stopWatch.stop();
		log.info("代码生成结束,耗时{}秒", stopWatch.getTotalTimeSeconds());
		System.exit(0);
	}


	private List<GenConfig> translateFromMapList(List<Map<String, String>> list) {
		List<GenConfig> configs = new ArrayList<>();
		for (Map<String, String> map : list) {
			GenConfig genConfig = BeanUtil.mapToBean(map, GenConfig.class, true);
			configs.add(genConfig);
		}
		return configs;
	}
}
